﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Common.Logging;
using log4net.Repository.Hierarchy;

namespace KeepAliveHttp.Http
{
    public class AsyncResult : IAsyncResult
    {
        private readonly ManualResetEvent _waitHandle;
        private static readonly ILog logger = LogManager.GetLogger(typeof(AsyncResult));
        public AsyncResult(HttpContext context, AsyncCallback cb, object extraData)
        {
            Context = context;
            CallBack = cb;
            ExtraData = extraData;
            _waitHandle = new ManualResetEvent(false);
        }
        public HttpContext Context
        {
            get;
            set;
        }
        public object ExtraData
        {
            get;
            set;
        }
        public AsyncCallback CallBack
        {
            get;
            set;
        }

        public bool IsCompleted { get; set; }
        public WaitHandle AsyncWaitHandle
        {
            get;
            set;
        }
        public object AsyncState
        {
            get;
            set;
        }
        public bool CompletedSynchronously
        {
            get { return false; }
        }
        /// <summary>
        /// 请求完成
        /// </summary>
        private void CompleteRequest()
        {
            this.IsCompleted = true;
            _waitHandle.Set();//通知其他等待线程
            CallBack?.Invoke(this);
        }
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _waitHandle.Dispose();
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message"></param>
        public void Send(string message)
        {
            if (this.IsCompleted)
            {
                return;
            }
            if (string.IsNullOrEmpty(message))
            {
                return;
            }
            try
            {
                this.Context.Response.ContentType = "text/plain";
                this.Context.Response.Write(message);
            }
            catch (Exception ex)
            {
                logger.Error("输出到客户端发生错误:" + ex.Message);
            }
            finally
            {
                this.CompleteRequest();
            }
        }
    }
}